package com.piece.core.framework.util.security.coder;

import lombok.extern.slf4j.Slf4j;
import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * Md5加密方法
 */
@Slf4j
public class MD5Coder {

    /**
     * 密钥算法
     */
    private static final String ENCRPTY_KEY = "MD5";

    private static byte[] md5(String s) {
        MessageDigest algorithm;
        try {
            algorithm = MessageDigest.getInstance(ENCRPTY_KEY);
            algorithm.reset();
            algorithm.update(s.getBytes(StandardCharsets.UTF_8));
            byte[] messageDigest = algorithm.digest();
            return messageDigest;
        } catch (Exception e) {
            log.error("MD5转换异常：{}", e.getMessage());
        }
        return null;
    }

    private static final String toHex(byte[] hash) {
        if (null == hash) {
            return null;
        }
        StringBuffer buf = new StringBuffer(hash.length * 2);
        int i;

        for (i = 0; i < hash.length; i++) {
            if ((hash[i] & 0xff) < 0x10) {
                buf.append("0");
            }
            buf.append(Long.toString(hash[i] & 0xff, 16));
        }
        return buf.toString();
    }

    /**
     * 加密方法
     */
    public static String decode(String s) {
        try {
            return new String(toHex(md5(s)).getBytes(StandardCharsets.UTF_8), StandardCharsets.UTF_8);
        } catch (Exception e) {
            log.error("MD5加密异常：{}", e.getMessage());
            return s;
        }
    }

    /**
     * 文件md5计算
     */
    public static String md5File(byte[] bytes) {
        byte[] code = new byte[0];
        try {
            code = MessageDigest.getInstance(ENCRPTY_KEY).digest(bytes);
        } catch (NoSuchAlgorithmException e) {
            return "";
        }
        BigInteger bi = new BigInteger(code);
        return bi.abs().toString(32).toUpperCase();
    }
}
